package com.linkgie.galaxyframework.httpproxy.core;

import java.io.Serializable;
import java.net.URL;
import java.util.Arrays;

import org.springframework.util.StringUtils;

import com.linkgie.galaxyframework.utils.TextUtils;

/**
 * HTTP 地址；
 * 
 * @author haiq
 *
 */
public class HttpAddress implements Cloneable, Serializable {
	
	private static final long serialVersionUID = 8704103344528870323L;

	private String host;

	private int port;

	private boolean secure;
	
	private String contextPath;
	
	public HttpAddress(URL url) {
		this(url.getHost(), url.getPort(), "https".equalsIgnoreCase(url.getProtocol()), url.getPath());
	}
	
	public HttpAddress(String host, int port, boolean secure) {
		this(host, port, secure, null);
	}
	
//	public HttpAddress(NetworkAddress networkAddress) {
//		this(networkAddress.getHost(), networkAddress.getPort(), networkAddress.isSecure(), null);
//	}
	
	public HttpAddress(String host, int port, boolean secure, String contextPath) {
//		super(host, port, secure);
		this.host = host;
		this.port = port;
		this.secure = secure;
		
		contextPath = StringUtils.cleanPath(contextPath);
		if (TextUtils.isEmpty(contextPath)) {
			this.contextPath = "/";
		}else{
			this.contextPath = contextPath;
		}
	}
	
	public String getContextPath() {
		return contextPath;
	}
	

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public boolean isSecure() {
		return secure;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public void setSecure(boolean secure) {
		this.secure = secure;
	}

	@Override
	public String toString() {
		return secure ? String.format("secure://%s:%s", host, port) : String.format("%s:%s", host, port);
	}

	@Override
	public int hashCode() {
		return Arrays.hashCode(new Object[] { host, port, secure });
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (obj instanceof HttpAddress) {
			HttpAddress other = (HttpAddress) obj;
			return this.host.equals(other.host) && this.port == other.port && this.secure == other.secure;
		}
		return false;
	}

	@Override
	public HttpAddress clone() {
		try {
			return (HttpAddress) super.clone();
		} catch (CloneNotSupportedException e) {
			throw new UnsupportedOperationException(e.getMessage(), e);
		}
	}

}
